<template>
  <!--Banner-->
  <div class="i_addBanner">
    <!-- <tmpHeader style='margin-bottom:10px;'/> -->
    <div class="main">
      <Form ref="formValidate" :model="formValidate" :rules="ruleValidate" :label-width="100">
        <FormItem label="banner名称：" prop="bannerName">
          <Input
            v-model.trim="formValidate.bannerName"
            placeholder="请输入医院banner图名称"
            style="width: 350px"
            maxlength="50"
          />
        </FormItem>
        <FormItem label="banner图片：">
          <div class="input">
            <div class="demo-upload-list" v-for="(item,index) in uploadList" :key="index">
              <div v-if="item.status === 'finished'">
                <img :src="item.url" v-if="item.url"/>
                <div class="demo-upload-list-cover">
                  <Icon type="ios-eye-outline" @click.native="handleView(item.name)"></Icon>
                  <Icon type="ios-trash-outline" @click.native="handleRemove(index)"></Icon>
                </div>
              </div>
              <div v-else>
                <Progress v-if="item.showProgress" :percent="item.percentage" hide-info></Progress>
              </div>
            </div>
            <Upload
              v-show="uploadList.length ==0"
              ref="upload"
              :show-upload-list="false"
              :default-file-list="defaultList"
              :on-success="handleSuccess"
              :format="['jpg','jpeg','png']"
              :max-size="1024"
              :on-format-error="handleFormatError"
              :on-exceeded-size="handleMaxSize"
              :before-upload="handleBeforeUpload"
              multiple
              type="drag"
              :action="uploadUrl"
              :headers="fromData"
              :data="uploadData"
              style="display: inline-block;width:58px;"
            >
              <div style="width: 58px;height:58px;line-height: 58px;">
                <Icon type="ios-camera" size="20"></Icon>
              </div>
            </Upload>
            <br>
            <small style="color:#FF9966;">备注：图片只能上传jpeg、png、jpg格式，且文件大小不超过1024KB</small>
            <Modal title="预览图片" v-model="visible" footer-hide :transfer="false">
              <img :src=" uploadList[0].url " v-if="visible" style="width: 100%;" />
            </Modal>
          </div>
        </FormItem>
        <FormItem label="banner链接：">
          <Input
            v-model.trim="formValidate.bannerUrl"
            placeholder="请输入banner链接"
            style="width: 350px"
            maxlength="180"
          />
        </FormItem>
        <FormItem label="显示配置：">
          <Select class="w-select" v-model="type">
           <Option v-for="(item,index) in tabList" :value="index" :key="index">{{item}}</Option>
        </Select>
        </FormItem>
        <FormItem label="排序：">
          <InputNumber
            :max="99999"
            :min="0"
            v-model.trim="formValidate.priority"
            style="width: 100px"
          ></InputNumber>
        </FormItem>
        <FormItem label="是否显示：">
          <iSwitch size="large"  v-model="formValidate.enable" >
              <span slot="open">显示</span>
              <span slot="close">关闭</span>
          </iSwitch>
        </FormItem>
        <div style="border-top: 1px dashed #999; margin: 0 -32px;padding: 10px 0px;"></div>
        <div  style="width:100%px;text-align:center;">
          <Button @click="save('formValidate')" type="primary" :disabled = 'disabled' style="width:75px;height:35px;">
              <Icon type="ios-checkmark" style="margin-right: 5px" />保存
            </Button>
          <Button @click="back" style="width:75px;height:35px;">
              <i class = "iconfont icon-butongyi" style="font-size:14px;margin-right:5px"></i>取消
        </Button>
        </div>
      </Form>
    </div>
  </div>
</template>

<script>
import tmpHeader from "@/pages/organizat/contentmen/tmpHeader";
import code from "@/configs/base.js";
import api from "@/api/commonApi";
export default {
  components: {
    tmpHeader
  },
  props:{
      itemid: {
      type: Number,
      default: () =>  Number
    },
  },
  data() {
    return {
      formValidate: {
        bannerName: "",
        bannerUrl: "",
        priority: null,
        enable: false
      },
      type:0,
      tabList:["全部","患者端","医生端"],
      ruleValidate: {
        bannerName: [
          { required: true, message: "请输入医院banner图名称", trigger: "blur" }
        ]
      },
      defaultList: [],
      imgName: "",
      visible: false,
      uploadList: [],
      id: sessionStorage.getItem("hospitalId"),
      uploadModal: true,
      uploadData: { json: '{"urlCode":"' + code.urlCode.hospitalBanner + '"}' },
      activeUploadId: "5c2bf345-b973-4ffd-a52e-87bb9c1d2b72",
      uploadUrl: api.fileAll,
      images: "",
      sourceImages: "",
      editid:'',
      disabled: false
    };
  },
  created() {
    let breadList = [
      { path: "/index", title: "首页" },
      {
        path: "/index/operation/mechanism/index",
        title: "机构运营"
      },
      {
        path: "/index/operation/home",
        title: "机构配置管理"
      }
    ];
    this.$emit("changeBreadList", breadList);
  },
  methods: {
    editBanner(param){
        this.editid = param
        // this.uploadList = this.$refs.upload.fileList;
        this.$axios.post(api.bannerById, {id:param}).then(res => {
            if (res.data.code) {
              let ret = res.data.object;
              this.type = Number(ret.type)
              this.formValidate.bannerName = ret.bannerName;
              this.formValidate.bannerUrl = ret.bannerUrl;
              this.formValidate.priority = ret.priority ? ret.priority :null;
              this.formValidate.enable = Boolean(ret.enable);
              //图片
              if (ret.imageUrl) {
                this.uploadList = []
                this.sourceImages = ret.imageUrl;
                this.uploadList.push({
                  name: "a42bdcc1178e62b4694c830f028db5c0",
                  percentage: 100,
                  status: "finished",
                  uid: 1544263544971,
                  url: this.fileBaseUrl + this.pictureFormat(ret.imageUrl)
                });
              }
            }
          })
          .catch(err => {
            console.log(err);
          });
    },
    // 弹出框关闭后触发
    handleClose(){
        // 子组件调用父组件方法，并传递参数
        this.$emit('changeShow','false')
    },
    onClose() {
      this.$emit('close')
      console.log(this.editModal)
    },
    change(status) {
      // this.$Message.info("开关状态：" + status);
    },
    back() {
       this.uploadList = []
      this.$emit('showeditModal');
      sessionStorage.removeItem('itemid')
    },
    save(name) {
      this.disabled = true
      this.$refs[name].validate(valid => {
        if (valid) {
          let images = "";
          // 上传
          if (this.images != "") {
            images = this.images;
          } else if (this.sourceImages != "" && this.uploadList.length) {
            images = this.sourceImages;
            // 默认
          } else {
            images = "";
          }
          let params = {
            hospitalId: this.id,
            type: this.type.toString(),
            bannerName: this.formValidate.bannerName.trim(),
            bannerUrl: this.formValidate.bannerUrl,
            priority: this.formValidate.priority,
            id: this.editid,
            enable: Number(this.formValidate.enable),
            imageUrl: images
          };
            this.$axios
              .post(api.bannerUpdate, params)
              .then(res => {
                if (res.data.code) {
                  this.$Message.info("修改成功");
                  this.formValidate = {}
                  this.uploadList = []
                  this.$emit('showeditModal');
                  let pageNo = this.$route.params.pageNo;
                  setTimeout(() => {
                    this.disabled = false
                  }, 1000);
                } else {
                  this.$Message.info("修改失败请重试");
                }
              })
              .catch(err => {
                console.log(err);
              });
        } else {
          this.$Message.error("请完整填写必填项!");
        }
      });
    },
    handleView(name) {
      this.imgName = name;
      this.visible = true;
    },
    handleRemove(file) {
      const fileList = this.$refs.upload.fileList;
      this.$refs.upload.fileList.splice(fileList.indexOf(file), 1);
       this.uploadList = []
       if(this.images) {
         this.images = ''
       }
    },
    handleSuccess(res, file) {
      console.log(res)
      res = this.uploadFileDecrypt(res);
      file.url = this.fileBaseUrl + res.object[0].fileName;
      this.images = JSON.stringify(res.object[0]);
      file.name = res.object[0].fileName;
      this.uploadList.push({
        name: "a42bdcc1178e62b4694c830f028db5c0",
        percentage: 100,
        status: "finished",
        uid: 1544263544971,
        url: this.fileBaseUrl + res.object[0].fileName
      });
    },
    handleFormatError(file) {
      this.$Notice.warning({
        title: "格式错误",
        desc: "文件 " + file.name + " 上传失败,请重试"
      });
    },
    handleMaxSize(file) {
      this.$Notice.warning({
        title: "文件过大",
        desc: '文件' + file.name +'过大，文件最大限制为1024KB'
      });
    },
    handleBeforeUpload() {
      const check = this.uploadList.length < 1;
      if (!check) {
        this.$Message.info("只能上传一张图片");
      }
      return check;
    },
  },
  mounted() {

  }
};
</script>


<style scoped lang="less">
.demo-upload-list {
  display: inline-block;
  width: 60px;
  height: 60px;
  text-align: center;
  line-height: 60px;
  border: 1px solid transparent;
  border-radius: 4px;
  overflow: hidden;
  background: #fff;
  position: relative;
  box-shadow: 0 1px 1px rgba(0, 0, 0, 0.2);
  margin-right: 4px;
}
.w-select{
  width: 100px;
}
.demo-upload-list img {
  width: 100%;
  height: 100%;
}
.demo-upload-list-cover {
  display: none;
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  background: rgba(0, 0, 0, 0.6);
}
.demo-upload-list:hover .demo-upload-list-cover {
  display: block;
}
.demo-upload-list-cover i {
  color: #fff;
  font-size: 20px;
  cursor: pointer;
  margin: 0 2px;
}
.i_addBanner {
  width: calc(100% - 20px);
  padding: 10px 0px;
  margin: 0 auto;
  background: #fff;
  .main {
      width: 100%;
      margin: 0 auto;
    }
}
</style>